package com.yonyou.distribute.service;


import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * p43
 */
@Slf4j
@Service
public class RedissonService_3 {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    public void testFairLock(Long id) {
        RLock fairLock = this.redissonClient.getFairLock("fairLock");
        fairLock.lock();
        try {
            TimeUnit.SECONDS.sleep(5);
            log.info("测试公平锁:" + id);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            fairLock.unlock();
        }
    }

    public void testReadLock() {
        RReadWriteLock lock = this.redissonClient.getReadWriteLock("rwLock");
        lock.readLock().lock(10, TimeUnit.SECONDS);
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
//            lock.readLock().unlock();
        }
    }

    public void testWriteLock() {
        RReadWriteLock lock = this.redissonClient.getReadWriteLock("rwLock");
        lock.writeLock().lock(10, TimeUnit.SECONDS);
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
//            lock.writeLock().unlock();
        }
    }

    public void testSemaphore() {
        RSemaphore rSemaphore = this.redissonClient.getSemaphore("semaphore");
        rSemaphore.trySetPermits(3);
        try {
            rSemaphore.acquire();
            this.stringRedisTemplate.opsForList().rightPush("log", "开始业务处理 " + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(10 + new Random().nextInt(10));
            this.stringRedisTemplate.opsForList().rightPush("log", "业务处理结束，释放资源 " + Thread.currentThread().getName());
            rSemaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 准备锁门
     */
    public void testLatch() {
        RCountDownLatch countDownLatch = this.redissonClient.getCountDownLatch("cdl");
        countDownLatch.trySetCount(5);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 出门
     */
    public void testCountdown() {
        RCountDownLatch countDownLatch = this.redissonClient.getCountDownLatch("cdl");
        countDownLatch.countDown();
    }
}
